/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package luft27.zorcon.input;

import luft27.propertytree.PropertyNode;
import luft27.propertytree.PropertyTree;
import luft27.propertytree.PropertyValue;
import luft27.util.RunnableLoop;

/**
 *
 * @author amalikov
 */
public class Input extends RunnableLoop {

	@Override
	public void init() {
		PropertyNode i = PropertyTree.INSTANCE.getNode("/settings/input");
		ailerons = new Control(i.getNode("/ailerons"));
		elevator = new Control(i.getNode("/elevator"));
		rudder = new Control(i.getNode("/rudder"));
		throttle = new Control(i.getNode("/throttle"));
		flaps0 = new Control(i.getNode("/flaps0"));
		flaps1 = new Control(i.getNode("/flaps1"));
		flaps2 = new Control(i.getNode("/flaps2"));
		ignitionOff = new Control(i.getNode("/ignition-off"));
		cmdAuto = new Control(i.getNode("/cmd-auto"), Control.TRIGGER);
		cmdManual = new Control(i.getNode("/cmd-manual"), Control.TRIGGER);
		cmdFutaba = new Control(i.getNode("/cmd-futaba"), Control.TRIGGER);
		cmdAbort = new Control(i.getNode("/cmd-abort"), Control.TRIGGER);
		cmdEmergency = new Control(i.getNode("/cmd-emergency"), Control.TRIGGER);
	}

	@Override
	public void cycle() {
		PropertyNode m = PropertyTree.INSTANCE.getNode("/vehicles/vehicle[0]/manualcontrols");
		m.set("/ailerons", new PropertyValue(ailerons.getValue()));
		m.set("/elevator", new PropertyValue(elevator.getValue()));
		m.set("/rudder", new PropertyValue(rudder.getValue()));
		m.set("/throttle", new PropertyValue(ignitionOff.getValue() > 0 ? -1 : 0.5f * throttle.getValue() + 0.5f));
		
		if (flaps0.getValue() > 0)
			m.set("/flaps", new PropertyValue(0));
		if (flaps1.getValue() > 0)
			m.set("/flaps", new PropertyValue(1));
		if (flaps2.getValue() > 0)
			m.set("/flaps", new PropertyValue(2));		
		
		PropertyNode c = PropertyTree.INSTANCE.getNode("/vehicles/vehicle[0]/commands");
		
		if (cmdAuto.getValue() > 0)
			c.set("/auto", new PropertyValue(true));
		if (cmdManual.getValue() > 0)
			c.set("/manual", new PropertyValue(true));
		if (cmdFutaba.getValue() > 0)
			c.set("/futaba", new PropertyValue(true));
		if (cmdAbort.getValue() > 0)
			c.set("/abort", new PropertyValue(true));
		if (cmdEmergency.getValue() > 0)
			c.set("/emergency", new PropertyValue(true));
		
		try {
			Thread.sleep(20);
		} catch (InterruptedException ex) {}
	}

	private Control ailerons;
	private Control elevator;
	private Control rudder;
	private Control throttle;
	private Control flaps0;
	private Control flaps1;
	private Control flaps2;
	private Control ignitionOff;
	private Control cmdAuto;
	private Control cmdManual;
	private Control cmdFutaba;
	private Control cmdAbort;
	private Control cmdEmergency;
}
